#!/bin/bash -x
set -x
ProgName=$(basename $0)
BaseDir=$(dirname $(readlink -f "$0"))

####################################################################################################################
# Helper functions
####################################################################################################################

red() {
    printf '\33[1;31m%b\n\33[0m' "$1"
}

green() {
    printf '\33[1;32m%b\n\33[0m' "$1"
}

ensure_sysom_conf_exists() {
    if [ ! -f "$SYSOM_CONF" ]
    then
        cp `dirname $BaseDir`/conf/config.yml $SYSOM_CONF
    fi
}

update_global_config() {
    sed "s/SERVER_LOCAL_IP: 127.0.0.1/SERVER_LOCAL_IP: $SERVER_LOCAL_IP/g" -i ${SYSOM_CONF}
    sed "s/SERVER_PUBLIC_IP: 127.0.0.1/SERVER_PUBLIC_IP: $SERVER_PUBLIC_IP/g" -i ${SYSOM_CONF}
    sed "s/SERVER_PORT: 80/SERVER_PORT: $SERVER_PORT/g" -i ${SYSOM_CONF}
    sed "s/global_root_path \/usr\/local\/sysom/global_root_path $APP_HOME/g" -i ${SYSOM_CONF}

    # MySQL
    if [ $DB_MYSQL_HOST ]; then
        sed "/mysql/,/host/s/host: localhost/host: $DB_MYSQL_HOST/g" -i ${SYSOM_CONF}
    fi
    if [ $DB_MYSQL_PORT ]; then
        sed "/mysql/,/port/s/port: 3306/port: $DB_MYSQL_PORT/g" -i ${SYSOM_CONF}
    fi
    if [ $DB_MYSQL_USERNAME ]; then
        sed "/mysql/,/user/s/user: sysom/user: $DB_MYSQL_USERNAME/g" -i ${SYSOM_CONF}
    fi
    if [ $DB_MYSQL_PASSWORD ]; then
        sed "/mysql/,/password/s/password: sysom_admin/password: $DB_MYSQL_PASSWORD/g" -i ${SYSOM_CONF}
    fi
    if [ $DB_MYSQL_DATABASE ]; then
        sed "/mysql/,/database/s/database: sysom/database: $DB_MYSQL_DATABASE/g" -i ${SYSOM_CONF}
    fi

    # Redis
    if [ $REDIS_HOST ]; then
        sed "/redis:/,/host/s/host: localhost/host: $REDIS_HOST/g" -i ${SYSOM_CONF}
    fi
    if [ $REDIS_PORT ]; then
        sed "/redis:/,/port/s/port: 6379/port: $REDIS_PORT/g" -i ${SYSOM_CONF}
    fi
    if [ $REDIS_USERNAME ]; then
        sed "/redis:/,/username/s/username:/username: $REDIS_USERNAME/g" -i ${SYSOM_CONF}
    fi
    if [ $REDIS_PASSWORD ]; then
        sed "/redis:/,/password/s/password:/password: $REDIS_PASSWORD/g" -i ${SYSOM_CONF}
    fi

    ###update local timezone###
    local_timezone=`timedatectl status | grep "Time zone" | awk '{print $3}'`
    green "current timezone is : $local_timezone"
    if [ "$local_timezone" == "" ]
    then
        echo "get time zone fail, use default time zone Asia/Shanghai"
    else
        sed "s;Asia/Shanghai;$local_timezone;g" -i ${SYSOM_CONF}
    fi
}

####################################################################################################################
# Subcommands
####################################################################################################################

sub_help(){
    echo "Usage: $ProgName <subcommand> [options]"
    echo "Subcommands:"
    echo "    all     Deploy all modules"
    echo "    infrastructure [ALL | <base_env_name>]        Deploy infrastructure components"
    echo "        Example: $ProgName infrastructure env"
    echo "        Example: $ProgName infrastructure local_services"
    echo "    microservice  [ALL | <service_name>]          Deploy all microservices or specific microservice"
    echo "        Example: $ProgName microservice sysom_diagnosis"
    echo ""
    echo "For help with each subcommand run:"
    echo "$ProgName <subcommand> -h|--help"
    echo ""
}

sub_all() {
    local_microservice_dir=$BaseDir/server
    # Load deploy_excludes
    deploy_excludes=""
    if [ -f "${local_microservice_dir}/deploy_exclude" ];then
        deploy_excludes=`cat ${local_microservice_dir}/deploy_exclude`
    fi
    # Deploy all microservices
    for microservice in $(ls $local_microservice_dir)
    do
        if [[ $deploy_excludes =~ $microservice ]] || [ ! -d "${local_microservice_dir}/${microservice}" ];then
            continue
        fi
        do_dbmigrate ${microservice}
    done
}

do_dbmigrate() {
    mkdir -p ${MICROSERVICE_HOME}
    local_microservice_dir=$BaseDir/server
    target=$1
    targets=(${target//,/ })
    for target in ${targets[*]}
    do
        for service_dir in $(ls ${local_microservice_dir} | grep ${target})
        do
            target_dir=${local_microservice_dir}/${service_dir}

            pushd ${target_dir}
            
            # update microservice common.py, replace {BASE_DIR.parent.parent}/conf/config.yml to ${SYSOM_CONF}
            if [ -f "${target_dir}/conf/common.py" ]; then
                sed -i "s;{BASE_DIR.parent.parent}/conf/config.yml;/etc/sysom/config.yml;g" ${target_dir}/conf/common.py
            fi
            # update fastapi based microservice alembic/env.py, replace {BASE_DIR.parent.parent}/conf/config.yml to ${SYSOM_CONF}
            if [ -f "${target_dir}/alembic/env.py" ]; then
                sed -i "s;{BASE_DIR.parent.parent}/conf/config.yml;/etc/sysom/config.yml;g" ${target_dir}/alembic/env.py
            fi
            # update microservice gunicorn.py replace /var/log/sysom to ${LOG_HOME}
            if [ -f "${target_dir}/conf/gunicorn.py" ]; then
                sed -i "s;/var/log/sysom;${LOG_HOME};g" ${target_dir}/conf/gunicorn.py
            fi

            green "$target_dir db migrate start..................................."
            if [ ! -f "${target_dir}/db_migrate.sh" ];then
                popd
                continue
            fi
            bash -x ${target_dir}/db_migrate.sh
            # if [ $? -ne 0 ];then
            #     red "$target_dir db migrate fail, please check..................................."
            #     red "sysom init failed, exit 1"
            #     exit 1
            # fi
            popd
        done
    done
}

subcommand=$1
case $subcommand in
    "" | "-h" | "--help")
        sub_help
        ;;
    "all" | "ALL")
        ensure_sysom_conf_exists
        update_global_config
        sub_all
        ;;
    *)
        ensure_sysom_conf_exists
        update_global_config
        do_dbmigrate $@
        if [ $? = 127 ]; then
            echo "Error: '$subcommand' is not a known subcommand." >&2
            echo "       Run '$ProgName --help' for a list of known subcommands." >&2
            exit 1
        fi
        ;;
esac